<?php
namespace app\admin\controller;

use app\common\component\notice\NoticeService;

class Notice extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	public function index() {
		$this -> view -> assign('notices', (new NoticeService) -> getNotices());

		return $this -> view -> fetch();
	}

	public function create() {
		if($this -> request -> isPost()) {
			$post = $this -> request -> post();
			$post['desc'] = htmlspecialchars($post['desc']);
			$post['create_time'] = time();

			$resultNotice = (new NoticeService()) -> create($post);
			if($resultNotice['code'] === 0) {
				echo '<meta charset="utf-8"><script>alert("发布成功!");window.location.href="/shuashuale/notice";</script>';exit;
			} else {
				$this -> error($resultNotice['message']);
			}
		}
		
		return $this -> view -> fetch();
	}

	public function update() {
		if($this -> request -> isPost()) {
			$post = $this -> request -> post();
			$post['desc'] = htmlspecialchars($post['desc']);

			$resultNotice = (new NoticeService()) -> update($post, $this -> request -> get('notice_id'));
			if($resultNotice['code'] === 0) {
				echo '<meta charset="utf-8"><script>alert("' . $resultNotice['message'] . '");window.location.href="/shuashuale/notice";</script>';exit;
			} else {
				$this -> error($resultNotice['message']);
			}
		}

		$resultNotice = (new NoticeService) -> getNotice($this -> request -> get('notice_id'));
		$this -> view -> assign('notice', $resultNotice['data']['notice']);

		return $this -> view -> fetch();
	}

	public function delete() {
		$resultNotice = (new NoticeService()) -> delete($this -> request -> get('notice_id'));
		if($resultNotice['code'] === 0) {
			echo '<meta charset="utf-8"><script>alert("' . $resultNotice['message'] . '");window.location.href="/shuashuale/notice";</script>';exit;
		} else {
			$this -> error($resultNotice['message']);
		}
	}
}